package com.ruoyi.web.controller.net;

import com.ruoyi.net.domain.ElementIsisPort;
import com.ruoyi.net.domain.ElementOspfv3PortNeighb;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementOspfv2;
import com.ruoyi.net.service.IElementOspfv2Service;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-OSPFV2进程配置-Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-OSPFV2进程配置-")
@RestController
@RequestMapping("/element/ospfv2")
public class ElementOspfv2Controller extends BaseController {
    @Autowired
    private IElementOspfv2Service elementOspfv2Service;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-OSPFV2进程配置-列表
     */
    @ApiOperation(value = "查询网元-OSPFV2进程配置-列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:ospfv2:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementOspfv2 elementOspfv2) {
        startPage();
        List<ElementOspfv2> list = elementOspfv2Service.selectElementOspfv2List(elementOspfv2);
        return getDataTable(list);
    }

    /**
     * 导出网元-OSPFV2进程配置-列表
     */
    @ApiOperation(value = "导出网元-OSPFV2进程配置-列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:ospfv2:export')")
    @Log(title = "网元-OSPFV2进程配置-", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementOspfv2 elementOspfv2) {
        List<ElementOspfv2> list = elementOspfv2Service.selectElementOspfv2List(elementOspfv2);
        ExcelUtil<ElementOspfv2> util = new ExcelUtil<ElementOspfv2>(ElementOspfv2.class);
        util.exportExcel(response, list, "网元-OSPFV2进程配置-数据");
    }

    /**
     * 获取网元-OSPFV2进程配置-详细信息
     */
    @ApiOperation(value = "获取网元-OSPFV2进程配置-详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:ospfv2:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementOspfv2Service.selectElementOspfv2ById(id));
    }

    /**
     * 新增网元-OSPFV2进程配置-
     */
    @ApiOperation(value = "新增网元-OSPFV2进程配置-", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:ospfv2:add')")
    @Log(title = "网元-OSPFV2进程配置-", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementOspfv2 elementOspfv2) {
        return toAjax(elementOspfv2Service.insertElementOspfv2(elementOspfv2));
    }

    /**
     * 修改网元-OSPFV2进程配置-
     */
    @ApiOperation(value = "修改网元-OSPFV2进程配置-", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:ospfv2:edit')")
    @Log(title = "网元-OSPFV2进程配置-", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementOspfv2 elementOspfv2) {
        return toAjax(elementOspfv2Service.updateElementOspfv2(elementOspfv2));
    }

    /**
     * 删除网元-OSPFV2进程配置-
     */
    @ApiOperation(value = "删除网元-OSPFV2进程配置-", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:ospfv2:remove')")
    @Log(title = "网元-OSPFV2进程配置-", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementOspfv2Service.deleteElementOspfv2ByIds(ids));
    }
    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementOspfv2 entity = elementOspfv2Service.selectElementOspfv2ById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementOspfv2Service.updateElementOspfv2(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementOspfv2 entity = elementOspfv2Service.selectElementOspfv2ById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementOspfv2Service.updateElementOspfv2(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    private boolean sendXml(ElementOspfv2 entity) {
        boolean isSend = true;
        // TODO: 2024/12/3  设备联调，添加并激活
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());

            String operation = "create";
            if ("0".equals(entity.getStatus())) {
                operation = "remove";
            }
            StringBuilder xml = new StringBuilder();
            xml.append("<ospf xmlns=\"http://fiberhome.com/fhnw/yang/ipprotocol/routing/fos-ospf\">" +
                    "    <ospf-processes>" +
                    "      <ospf-process nc:operation=\"" + operation + "\">" +
                    "        <process-id>" + entity.getOspfId() + "</process-id>" +
                    // ------- start 对等体 ------

            /*for (ElementOspfv2PortNeighb neighb : entity.getOspfv2NeighborList()) {
                xml.append("                <ospf-neighbor>")
                        .append("               <address>").append(neighb.getIp()).append("</address>") // TODO: 2024/12/3  address是否需要加入mask
                        .append("               <priority>").append(neighb.getLevel()).append("</priority>")
                        .append("               <poll-interval>").append(neighb.getHelloInterval()).append("</poll-interval>")
                        .append("               <cost>").append(neighb.getProtCost()).append("</cost>")
                        .append("               <ospf-neighbor>");
            }*/
                    // ------- end 对等体 --------
                    // -------start AS引入外部路由
                    /*"        <asbr-summary>" +
                    "           <summary-prefix></summary-prefix>" +
                    "           <not-advertise></not-advertise>" +
                    "       </asbr-summary>" +*/
                    // -------end AS引入外部路由
                    // ------ start 路由重分发 ------
                   /* "        <ospf-redistribute>" +
                    "          <protocol>connect</protocol>" +
                    "          <ospf-process-id>0</ospf-process-id>" +
                    "          <isis-process-name>nil</isis-process-name>" +
                    "        </ospf-redistribute>" +*/
                    // ------ end 路由重分发 ------
                    "        <capablity-te>"+entity.getTeEnable()+"</capablity-te>" +
                    "        <capability-shortcut>"+entity.getShortcutEnable()+"</capability-shortcut>" +
                    "        <compatible-rfc1583>"+entity.getRfc()+"</compatible-rfc1583>" +
                    "        <capability-opaque>"+entity.getOpaqueLspEnable()+"</capability-opaque>" +
                    "        <capability-cspf>"+entity.getCspfEnable()+"</capability-cspf>" +
                    "        <capability-vrf-simple>"+entity.getRingEnable()+"</capability-vrf-simple>" +
                    "        <route-id>"+ entity.getRouteId()+"</route-id>" +
                    "        <max-ecmp-path>"+entity.getMaxEqualRouteNum()+"</max-ecmp-path>" +
                    "        <distance>" +
//                    "          <admin-distance>"+entity.getDistanceConfig().split("|")[0]+"</admin-distance>" +
//                    "          <intra-distance>"+entity.getDistanceConfig().split("|")[1]+"</intra-distance>" +
//                    "          <inter-distance>"+entity.getDistanceConfig().split("|")[2]+"</inter-distance>" +
//                    "          <external-distance"+entity.getDistanceConfig().split("|")[3]+"</external-distance>" +
                    "        </distance>" +
                    "        <spf-intelligent-timer>" +
//                    "          <spf-start-interval>"+entity.getSpfTimer().split("|")[0]+"</spf-start-interval>" +
//                    "          <spf-hold-interval>"+entity.getSpfTimer().split("|")[1]+"</spf-hold-interval>" +
//                    "          <spf-max-wait-interval>"+entity.getSpfTimer().split("|")[2]+"</spf-max-wait-interval>" +
                    "        </spf-intelligent-timer>" +
                    "        <sr-mpls-enable>"+entity.getSrMplsEnable()+"</sr-mpls-enable>" +
                    // --- 配置SR标签优先 ，原型中不需要了
                    /*"        <sr-prefer>" +
                    "          <sr-prefer-enable>disable</sr-prefer-enable>" +
                    "        </sr-prefer>" +*/
                    //---- start 域配置 ---
                    /*"        <area>" +
                    "          <area-id>1.2.3.45</area-id>" +
                    "          <area-type>stub</area-type>" +
                    "          <stub-no-summary>true</stub-no-summary>" +
                    "        </area>" +*/
                    //---- end 域配置 ----
                    "        <bgp-ls>" +
//                    "          <bgp-ls-enable>"+entity.getBgpLs().split("|")[0]+"</bgp-ls-enable>" +
//                    "          <bgp-ls-time>"+entity.getBgpLs().split("|")[1]+"</bgp-ls-time>" +
                    "        </bgp-ls>" +
                    "        <ospf-frr>" +
//                    "          <lfa-flag>"+entity.getIpFrr().split("|")[0]+"</lfa-flag>" +
//                    "          <rlfa-flag>"+entity.getIpFrr().split("|")[1]+"</rlfa-flag>" +
//                    "          <tilfa-flag>"+entity.getIpFrr().split("|")[2]+"</tilfa-flag>" +
//                    "          <protect-type>"+entity.getIpFrr().split("|")[3]+"</protect-type>" +
                    "        </ospf-frr>" +
                    "        <micro-loop-avoidance/>" +
                    "        <sid-map-receive/>" +
                    "        <sid-map-advertise-local/>" +
                    "        <bfd-ospf-all xmlns=\"http://fiberhome.com/fhnw/yang/oam/fos-bfd\"/>" +
                    "      </ospf-process>" +
                    "    </ospf-processes>" +
                    "  </ospf>");
            System.out.println(xml.toString());
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }

}